'''
* Author       : LiuYuhai
* Date         : 2023-06-21
* Description  : For autotest
'''
import sys
import prettytable as pt

key = ["list(counts.items())", "txt"]

'''
func: 输入值文本判断
parm: 
return {*}
'''
def getFileName():
    try:
        fileName=sys.argv[1]
        return fileName
    except Exception as e:
        print("\nTry 'python compute.py <file_name>'\n")
        sys.exit()

'''
func: 读取文件内容 
parm: 
return {*}
'''
def getFileText(fileName):
    try:
        txt = open(fileName,"r",encoding="utf-8").read()

        #将文本中特殊字符替换为空格
        # for ch in '!"#$%&()*+,-./;:<=>?@[\\]^‘_{|}~':
        #     txt = txt.replace(ch," ")
        return txt

    except IOError as e:
        print ("ERROR: %s"%str(e))
        sys.exit()

'''
func: 统计命中字符串
parm: 
return {*}
'''
def countWords(txt):
    words = txt.split()
    counts={}
    for word in words:
        # print("word = ", word)
        for i in range(len(key)):
            if word == key[i]:
                counts[word] = counts.get(word,0)+1

    items = list(counts.items())
    items.sort(key=lambda x :x[1],reverse=True)

    # 输出格式
    table = pt.PrettyTable(['WORD', 'COUNT'])
    table.align = 'l'; #左对齐

    total = 0
    for i in range(len(items)):
        table.add_row(items[i])
        total+=items[i][1]

    table.add_row(["----------", ""])
    table.add_row(["Total: ", total])
    print(table)

    # print("\n")
    # print("{0:<20} {1:>10}".format("|**WORD**|","|**COUNT**|"))
    # for i in range(len(items)):
    #     word,count = items[i]
    #     print("{0:<20} {1:>5}".format(word,count))
    
    # print("total %d hits" %len(items))

    return len(items)

'''
func: 入口函数
parm: 
return {*}
'''
if __name__ == "__main__":
    filepath = getFileName();
    txt = getFileText(filepath)
    countWords(txt)
